package cn.fl.finance.controller;

import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.finance.api.IFinPayFeeApiService;
import cn.fl.finance.api.IFinRepayDtlApiService;
import cn.fl.finance.condition.FinRepayApplyInfoQC;
import cn.fl.finance.constant.FinFlowModelConstant;
import cn.fl.finance.constant.FinRepayApplyInfoConstant;
import cn.fl.finance.dto.FinRepayApplyInfoDTO;
import cn.fl.finance.service.IFinRepayApplyInfoService;
import cn.fl.finance.util.BaseResultVO;
import cn.fl.finance.util.FlowStartParmsVO;
import cn.fl.finance.vo.FinRepayApplyInfoVO;
import cn.fl.finance.vo.FinRepayDtlVO;
import cn.fl.finance.vo.FinRmtRecVO;
import cn.fl.flow.vo.SysFlowRejRsnVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.service.ISysUlFilesRecService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import fl.carloan.facade.carloan.constant.OdrBscInfoConstant;
import fl.flow.facade.flow.api.IFlowApiService;
import fl.flow.facade.flow.condition.SysFlowManageVQueryCondition;
import fl.flow.facade.flow.dto.SysFlowManageVDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description: 还款申请信息表 控制层
 */
@Controller
@RequestMapping("/finance/finRepayApplyInfo")
public class FinRepayApplyInfoController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(FinRepayApplyInfoController.class);

	/**
	 * FinRepayApplyInfo 服务层BEAN
	 */
	@Autowired
	private IFinRepayApplyInfoService finRepayApplyInfoService;

	@Autowired
	private IFinPayFeeApiService finPayFeeApiService;

	@Autowired
	private IFinRepayDtlApiService finRepayDtlApiService;


	@Autowired
	private IFlowApiService flowApiService;
    /**
     * 附件服务
     */
    @Autowired
    private ISysUlFilesRecService sysUlFilesRecService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("finance/finRepayApplyInfo/list");
		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}

    /**
     * 到还款申请页面
     */
    @RequestMapping(value = "/toRepayApplyPage.do", method = { RequestMethod.GET})
    public ModelAndView toRepayApplyPage(HttpServletRequest request, HttpServletResponse response) {
        String paydtlRIds = request.getParameter("paydtlRIds");//付款明细关联表id
        ModelAndView view = new ModelAndView("finance/finRepayApplyInfo/finRepayApply");
        List<KeyValueVO> myComBankList = this.finRepayApplyInfoService.searchCdListByLvl(FinRepayApplyInfoConstant.MY_COMPANY_BANK_ACC, 1);
        view.addObject("paydtlRIds", paydtlRIds);
        view.addObject("myComBankListJSON", JSON.toJSON(myComBankList));

        BaseLogUtils.info(logger, "toRepayApplyPage", "到还款申请页面.", CurrentThreadContext.getCurrentUserName());
        return view;
    }

    /**
     * 到还款申请记录页面
     */
    @RequestMapping(value = "/toRepayHisPage.do", method = { RequestMethod.GET})
    public ModelAndView toRepayHisPage(HttpServletRequest request, HttpServletResponse response) {
        String paySchDtlId = request.getParameter("paySchDtlId");//支付明细id
        String repayDtlId = request.getParameter("repayDtlId");//还款明细id

        ModelAndView view = new ModelAndView("finance/finRepayApplyInfo/finRepayApplyHis");
        view.addObject("paySchDtlId", paySchDtlId);
        view.addObject("repayDtlId", repayDtlId);

        BaseLogUtils.info(logger, "toRepayApplyPage", "到还款申请记录页面.", CurrentThreadContext.getCurrentUserName());
        return view;
    }

    /**
	 * 到还款流程附加页面
	 */
	@RequestMapping(value = "/toRepayApplyFlowPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toRepayApplyFlowPage(HttpServletRequest request, HttpServletResponse response) {
		String repayId = request.getParameter("repayId");//还款
		String isTuiHiden = request.getParameter("isTuiHiden");//退款隐藏   1显示
		String isBoundFunds = request.getParameter("isBoundFunds");//资金绑定节点   1表示显示 其他表示不可编辑
		String isTuiPay = request.getParameter("isTuiPay");//editFlag
		String editFlag = request.getParameter("editFlag");
		if(StringUtils.isEmpty(isTuiPay)){
			isTuiPay="0";
		}
		if(StringUtils.isEmpty(isTuiHiden)){
			isTuiHiden="0";
		}
		if(StringUtils.isEmpty(isBoundFunds)){
			isBoundFunds="0";
		}
		
		if(StringUtils.isEmpty(editFlag)){
			editFlag="0";
		}
		ModelAndView view = new ModelAndView("finance/finRepayApplyInfo/finRepayApplyFlowPage");
		if(StringUtils.isNotEmpty(repayId)) {
			Long usedAmount = this.finPayFeeApiService.selectCapUsedAmount(Long.valueOf(repayId));
			//Long usedAmount = this.finPayFeeApiService.selectCapUsedAmount(Long.valueOf("1"));
			view.addObject("usedAmount", usedAmount);
			FinRepayApplyInfoVO finRepayApplyInfoVO = this.finRepayApplyInfoService.selectById(Long.valueOf(repayId));
			view.addObject("handleWayCd", finRepayApplyInfoVO.getHandleWayCd());
        }
        view.addObject("repayId", repayId);
        view.addObject("isTuiHiden", isTuiHiden);
        view.addObject("isBoundFunds", isBoundFunds);
        view.addObject("isTuiPay", isTuiPay);
        view.addObject("editFlag", editFlag);
        //获取我司银行
        List<KeyValueVO> myComBankList = this.finRepayApplyInfoService.searchCdListByLvl(FinRepayApplyInfoConstant.MY_COMPANY_BANK_ACC, 1);
        view.addObject("myComBankListJSON", JSON.toJSON(myComBankList));


        BaseLogUtils.info(logger, "toRepayApplyFlowPage", "到还款流程附加页面.[repayId="+repayId+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("finance/finRepayApplyInfo/modify");
		view.addObject("id", id);
		BaseLogUtils.info(logger, "toModifyPage", "跳转到修改页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}
	 /**
     * 银行卡绑定List
     * @param model
     * @param payDtlId 付款明细id
     * @return
     */
    @RequestMapping("toBankListPage.do")
    public ModelAndView toList(ModelAndView model,@RequestParam(required = true) Long repayId){
       model.setViewName("finance/finRepayApplyInfo/repayApplyBankAccountList");
       model.addObject("repayId",repayId);
       return model;
    }



	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String searchName = request.getParameter("demo.name");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		FinRepayApplyInfoQC qc = new FinRepayApplyInfoQC();
		if (StringUtils.isNotEmpty(searchName)) {
			//TODO SOMTHING
		}
		page.setCondition(qc);

		//TODO SOMETHING
		Pager pager = new Pager();//this.finRepayApplyInfoService.searchListPage(page);
		List<FinRepayApplyInfoVO> list = (List<FinRepayApplyInfoVO>) pager.getResultList();
		ListPageVO<FinRepayApplyInfoVO> listPage = new ListPageVO<FinRepayApplyInfoVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.finRepayApplyInfoService.removeById(Long.valueOf(id));
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

    /**
     * 查询借款付款信息
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/selectPayInfo.do", method = { RequestMethod.GET})
    @ResponseBody
    public Object selectPayInfo(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String paydtlRIds = request.getParameter("paydtlRIds");
        String repayId = request.getParameter("repayId");

        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        ListPageVO<FinRepayApplyInfoVO> listPage = null;
        if(StringUtils.isEmpty(paydtlRIds) && StringUtils.isEmpty(repayId)){
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_PARAM_IS_BAD);
            BaseLogUtils.error(logger, "selectPayInfo", "请选择还款数据", CurrentThreadContext.getCurrentUserName());
            return result;
        }
        List<Long> idList = null;

        try {
            if (StringUtils.isNotBlank(paydtlRIds)) {
                String[] idArray = paydtlRIds.split(",");
                idList = new ArrayList<>(idArray.length);
                for (String id : idArray) {
                    if (StringUtils.isNotEmpty(id)) {
                        idList.add(Long.parseLong(id));
                    }
                }
            }

            FinRepayApplyInfoQC finRepayApplyInfoQC = new FinRepayApplyInfoQC();
            if (CollectionUtils.isNotEmpty(idList)) {
                finRepayApplyInfoQC.setIdList(idList);
            }
            if (StringUtils.isNotEmpty(repayId)) {
                finRepayApplyInfoQC.setRepayId(Long.valueOf(repayId));
            }

            List<FinRepayApplyInfoVO> vo = this.finRepayApplyInfoService.selectPayInfoByQc(finRepayApplyInfoQC);
            if(null == vo){
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
                BaseLogUtils.info(logger, "selectPayInfo", "获取数据,数据不存在.[id="+idList+"]", CurrentThreadContext.getCurrentUserName());
            }
            listPage = new ListPageVO<FinRepayApplyInfoVO>((List<FinRepayApplyInfoVO>) vo, vo.size());
            result.setData(vo);
            BaseLogUtils.info(logger, "selectPayInfo", "获取数据.[id="+idList+"]", CurrentThreadContext.getCurrentUserName());
        }catch(BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "selectPayInfo", "获取失败.[id="+idList+"]"+ex, CurrentThreadContext.getCurrentUserName());
        }catch(Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "selectPayInfo", "获取失败.[id="+idList+"]"+ex, CurrentThreadContext.getCurrentUserName());
        }
        return listPage;
    }

    /**
     * 根据支付明细ID查询还款申请记录
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/selectRepayHis.do", method = { RequestMethod.GET})
    @ResponseBody
    public Object selectRepayHis(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String paySchDtlId = request.getParameter("paySchDtlId");//支付表明细ID
        String repayDtlId = request.getParameter("repayDtlId");//还款明细ID

        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        ListPageVO<FinRepayApplyInfoVO> listPage = null;
        if(StringUtils.isEmpty(paySchDtlId)){
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_PARAM_IS_BAD);
            BaseLogUtils.error(logger, "selectRepayHis", "参数不完整", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        try {
            FinRepayApplyInfoQC finRepayApplyInfoQC = new FinRepayApplyInfoQC();
            finRepayApplyInfoQC.setPaySchDtlId(Long.valueOf(paySchDtlId));
            if (StringUtils.isNotEmpty(repayDtlId)) {
                finRepayApplyInfoQC.setRepayDtlId(Long.valueOf(repayDtlId));
            }
            List<FinRepayApplyInfoVO> vo = this.finRepayApplyInfoService.selectRepayHis(finRepayApplyInfoQC);
            if(null == vo){
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
                BaseLogUtils.info(logger, "selectRepayHis", "获取数据,数据不存在.[paySchDtlId="+paySchDtlId+"]", CurrentThreadContext.getCurrentUserName());
            }
            listPage = new ListPageVO<FinRepayApplyInfoVO>((List<FinRepayApplyInfoVO>) vo, vo.size());
            result.setData(vo);
            BaseLogUtils.info(logger, "selectRepayHis", "获取数据.[paySchDtlId="+paySchDtlId+"]", CurrentThreadContext.getCurrentUserName());
        }catch(BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "selectRepayHis", "获取失败.[paySchDtlId="+paySchDtlId+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }catch(Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "selectRepayHis", "获取失败.[paySchDtlId="+paySchDtlId+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return listPage;
    }

    /**
     * 根据我司收款银行获取我司收款账号
     */
    @RequestMapping(value = "/getMyComAccListJSON.do", method = { RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public Object getMyComAccListJSON(HttpServletRequest request, HttpServletResponse response){
        String acceptBkCd = request.getParameter("acceptBkCd");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        if( StringUtils.isEmpty(acceptBkCd)){
            BaseLogUtils.error(logger, "getMyComAccListJSON", "获取数据,缺少参数.[acceptBkCd="+acceptBkCd+"]", CurrentThreadContext.getCurrentUserName());
            return result;
        }
        try{
            List<KeyValueVO> myComAccList = this.finRepayApplyInfoService.searchChild("FIN10006", acceptBkCd);
            result.setData(JSONObject.toJSON(myComAccList));
        }catch(BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "getMyComAccListJSON", "获取失败.[acceptBkCd="+acceptBkCd+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }catch(Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "getMyComAccListJSON", "获取失败.[acceptBkCd="+acceptBkCd+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }

        return result;
    }

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			FinRepayApplyInfoVO vo = this.finRepayApplyInfoService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String repayInfo = request.getParameter("repayInfo");//还款明细
        String rmtInfo = request.getParameter("rmtInfo");//打款记录
        String repayRem = request.getParameter("repayRem");//备注

        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "还款申请发起成功！");
		FinRepayApplyInfoVO entity = null;
		try {
            List<FinRepayDtlVO> finRepayDtlVOS = new ArrayList<>();
            List<FinRmtRecVO> finRmtRecVOS = new ArrayList<>();

            if (StringUtils.isNotBlank(repayInfo)) {
                finRepayDtlVOS = JSON.parseArray(repayInfo, FinRepayDtlVO.class);
            }
            if (StringUtils.isNotBlank(rmtInfo)) {
                finRmtRecVOS = JSON.parseArray(rmtInfo, FinRmtRecVO.class);
            }
			entity = new FinRepayApplyInfoVO();
            if (StringUtils.isNotEmpty(repayRem)) {
                entity.setRepayRem(repayRem);
            }
            entity.setRepayTm(new Date());
            entity.setRepayStsCd(FinRepayApplyInfoConstant.REPAYMENT_IN);//还款中
            entity.setCstMgrId(CurrentThreadContext.getCurrentUserId());
            entity.setCstMgrNm(CurrentThreadContext.getCurrentUserName());
            entity.setCstMgrOrgCd(CurrentThreadContext.getCurrentOrgCd());
            entity.setBuOrgCd(CurrentThreadContext.getCurrentBuOrgCd());
            entity.setOrgDispNm(CurrentThreadContext.getCurrentOrgDispNm());
            entity.setSysCd(CurrentThreadContext.getCurrentSysCd());
            entity.setIsDel(BaseConstant.IS_YESNO_NO);
            entity.setCrtTm(new Date());
            entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
            entity.setCstMgrRgnCd(CurrentThreadContext.getCurrentRgnDivCd());
            //其他数据
            entity.setFinRepayDtlVOS(finRepayDtlVOS);
            entity.setFinRmtRecVOS(finRmtRecVOS);
			Long id = this.finRepayApplyInfoService.add(entity);
			if (StringUtils.isEmpty(id)) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("还款申请发起失败！");
                BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
                return result;
            }
            //上传 附件
            if (StringUtils.isNotEmpty(id)) {
                uploadAttchment(request, result, id);
            }
			result.setData(id);
			BaseLogUtils.info(logger, "add", "新增数据.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String id = request.getParameter("repayId");//还款申请Id
        String repayInfo = request.getParameter("repayInfo");//还款明细
        String rmtInfo = request.getParameter("rmtInfo");//打款记录
        String repayRem = request.getParameter("repayRem");//备注
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		FinRepayApplyInfoVO entity = null;
		try {
            List<FinRepayDtlVO> finRepayDtlVOS = new ArrayList<>();
            List<FinRmtRecVO> finRmtRecVOS = new ArrayList<>();

            if (StringUtils.isNotBlank(repayInfo)) {
                finRepayDtlVOS = JSON.parseArray(repayInfo, FinRepayDtlVO.class);
            }
            if (StringUtils.isNotBlank(rmtInfo)) {
                finRmtRecVOS = JSON.parseArray(rmtInfo, FinRmtRecVO.class);
            }
            entity = new FinRepayApplyInfoVO();
            entity.setId(Long.valueOf(id));
            if (StringUtils.isNotEmpty(repayRem)) {
                entity.setRepayRem(repayRem);
            }
            entity.setMdfTm(new Date());
            entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
            //其他数据
            entity.setFinRepayDtlVOS(finRepayDtlVOS);
            entity.setFinRmtRecVOS(finRmtRecVOS);
			boolean success = this.finRepayApplyInfoService.modify(entity);

			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
            //上传 附件
            uploadAttchment(request, result, Long.valueOf(id));
			BaseLogUtils.info(logger, "modify", "修改成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	
	/**
	 * 还款流程
	 */
	@RequestMapping(value = "/addFlowStart.do", method = { RequestMethod.POST})
	@ResponseBody
	public Object addFlowStart(HttpServletRequest request, HttpServletResponse response) {
		
		String id = request.getParameter("id");
		BaseResultVO result = new BaseResultVO("操作成功");
		if (StringUtils.isEmpty(id)) {
			result.setInfo("操作失败");
			result.setError("id不能为空");
			return result;
		}
		// 查询流程最新版本
		SysFlowManageVQueryCondition flowManaQC = new SysFlowManageVQueryCondition();
		flowManaQC.setSysCd(OdrBscInfoConstant.SYS_CD);
		flowManaQC.setIsDel(BaseConstant.IS_YESNO_NO);
		flowManaQC.setIsValid(BaseConstant.IS_YESNO_YES);
		flowManaQC.setModelTyp(FinFlowModelConstant.FLOW_MODEL_REPAYMENT);
		// flowManaQC.setOrgCd(odrBscInfoDTO.getCstMgrOrgCd());
		flowManaQC.setProcDefKey(FinFlowModelConstant.FLOW_REPAYMENT_PRE_ID);
		List<SysFlowManageVDTO> flowManageVListForStart = this.flowApiService.searchFlowManageVListForStart(flowManaQC);
		if (CollectionUtils.isEmpty(flowManageVListForStart)) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("未查询到可用的流程版本.");
			BaseLogUtils.info(
					logger, "addFlowStart", "=flowManaQC : " + JSON.toJSONString(flowManaQC)
							+ "=flowManageVListForStart : " + JSON.toJSONString(flowManageVListForStart),
					CurrentThreadContext.getCurrentUserName());
			return result;
		}
		SysFlowManageVDTO sysFlowManageVDTO = flowManageVListForStart.get(0);

		FlowStartParmsVO vo = new FlowStartParmsVO();
		vo.setId(id);
		vo.setProcDefId(sysFlowManageVDTO.getProcDefId());
		vo.setProcDefKey(sysFlowManageVDTO.getProcDefKey());
		vo.setProcNo(sysFlowManageVDTO.getProcNo());

		// 接口调用 dto字段 code 200 标识交互成功
		DataResultDTO dto = finRepayApplyInfoService.addFlowStart(vo);
		if (!dto.getCode().equals("200")) {
			result.setInfo("操作失败");
			result.setError(dto.getInfo());
		}
		return result;
	}

    private void uploadAttchment(HttpServletRequest request, DataResultVO result, Long id) {
        String attchmnt = request.getParameter("fileParams");
        if(StringUtils.isNotEmpty(attchmnt)){
            //上传解析
            try{
                String cfgCd = FinRepayApplyInfoConstant.FIN_REPAY_APPLY_CFGCD;
                String cfgDtlCd = FinRepayApplyInfoConstant.FIN_REPAY_APPLY__CFGDTLCD_10;
                String tabNm = FinRepayApplyInfoConstant.FIN_REPAY_APPLY_INFO;
                String cfgOrgCd = FinRepayApplyInfoConstant.FIN_REPAY_APPLY_CFGORG;
                Boolean attchmntPass = this.sysUlFilesRecService.addAttchmnt(String.valueOf(id), attchmnt, cfgCd, cfgDtlCd, tabNm, "还款申请附件!", null, null, false, cfgOrgCd);
                if(null == attchmntPass || attchmntPass == false){
                    result.setInfo(result.getInfo()+"-附件上传失败!");
                }
            }catch(Exception e){
                BaseLogUtils.error(logger, "uploadAttchment", result.getInfo()+"-附件上传失败!", e);
                result.setInfo(result.getInfo()+"-附件上传失败!");
            }
        }
    }

	/**
	 * 到还款明细列表页面
	 */
	@RequestMapping(value = "/toDetailList.do", method = { RequestMethod.GET})
	public ModelAndView toDetailList(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("finance/finRepayApplyInfo/finRepayApplyDetail");
		String payDtlRId = request.getParameter("payDtlRId");//付款明细资产关联表id
		view.addObject("payDtlRId",payDtlRId);
		BaseLogUtils.info(logger, "toDetailList", "跳转到还款明细.", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 还款明细列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/selectDetailList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object selectDetailList(HttpServletRequest request, HttpServletResponse response) {
		String payDtlRId = request.getParameter("payDtlRId");//付款明细资产关联表id
		FinRepayApplyInfoQC qc = new FinRepayApplyInfoQC();
		if (StringUtils.isNotEmpty(payDtlRId)) {
			qc.setPayDtlRId(Long.valueOf(payDtlRId));
		}
		try{
			List<FinRepayApplyInfoDTO> finRepayApplyInfoDTOS = this.finRepayApplyInfoService.selectDetailList(qc);
			BaseLogUtils.info(logger, "selectDetailList", "查询数据完成. DATA:" + JSONObject.toJSONString(finRepayApplyInfoDTOS), CurrentThreadContext.getCurrentUserName());
			ListPageVO<FinRepayApplyInfoDTO> listPage = new ListPageVO<FinRepayApplyInfoDTO>(finRepayApplyInfoDTOS, finRepayApplyInfoDTOS.size());
			return listPage;
		}catch (Exception ex) {
			BaseLogUtils.info(logger, "selectDetailList", "还款明细查询数据失败：" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return  null;
	}
}

